﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using StuWebApi.Dto;
using StuWebApi.Entity;

namespace StuWebApi.Controllers;

[ApiController]
[Route("[controller]")]
public class SchoolsController : ControllerBase
{
    private readonly ApplicationDbContext _context;

    public SchoolsController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<School>>> GetSchools()
    {
        return await _context.Schools.ToListAsync();
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<School>> GetSchool(int id)
    {
        var school = await _context.Schools.FindAsync(id);
        if (school == null)
        {
            return NotFound();
        }
        return school;
    }

    [HttpPost]
    public async Task<ActionResult<School>> PostSchool(SchoolDto schoolDto)
    {
        var school = new School
        {
            Name = schoolDto.Name
        };

        _context.Schools.Add(school);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetSchool), new { id = school.SchoolId }, school);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> PutSchool(int id, SchoolDto schoolDto)
    {
        var school = await _context.Schools.FindAsync(id);
        if (school == null)
        {
            return NotFound();
        }

        school.Name = schoolDto.Name;

        _context.Entry(school).State = EntityState.Modified;
        await _context.SaveChangesAsync();

        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteSchool(int id)
    {
        var school = await _context.Schools.FindAsync(id);
        if (school == null)
        {
            return NotFound();
        }

        _context.Schools.Remove(school);
        await _context.SaveChangesAsync();

        return NoContent();
    }
}
